const jwt = require('jsonwebtoken');
require('dotenv').config();

module.exports = function (req, res, next) {
  // allow unauthenticated access to public endpoints used by the login page
  try {
    const url = req.originalUrl || req.url || '';
    if (url.startsWith('/public') || url === '/api/configs/网站名称' || url === '/api/configs/网站名称/') {
      return next();
    }
  } catch (e) {
    // ignore and continue to auth checks
  }

  const authHeader = req.headers['authorization'] || req.headers['Authorization'];
  if (!authHeader) return res.status(401).json({ message: 'No token provided' });
  const parts = authHeader.split(' ');
  if (parts.length !== 2 || parts[0] !== 'Bearer') return res.status(401).json({ message: 'Invalid token format' });
  const token = parts[1];
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded;
    next();
  } catch (err) {
    return res.status(401).json({ message: 'Invalid token' });
  }
};